﻿using Autofac;

namespace Quickuse.Ioc
{
    /// <summary>
    /// 依赖性解析器
    /// </summary>
    public class DependencyResolver
    {
        /// <summary>
        /// 容器
        /// </summary>
        private static IContainer _current;

        /// <summary>
        /// Set Resolver
        /// </summary>
        /// <param name="container"></param>
        public static void SetResolver(IContainer container)
        {
            _current = container;
        }

        /// <summary>
        /// Set Resolver
        /// </summary>
        /// <param name="lifetimeScope"></param>
        public static void SetResolver(ILifetimeScope lifetimeScope)
        {
            _current = (IContainer)lifetimeScope;
        }

        /// <summary>
        /// 发现服务
        /// </summary>
        /// <typeparam name="T">interface</typeparam>
        /// <returns></returns>
        public static T Resolve<T>()
        {
            if (_current.IsRegistered<T>())
            {
                return _current.Resolve<T>() ?? default;
            }
            else
            {
                return default;
            }
        }

        /// <summary>
        /// 发现服务
        /// </summary>
        /// <typeparam name="T">interface</typeparam>
        /// <param name="named">named</param>
        /// <returns></returns>
        public static T Resolve<T>(string named)
        {
            var obj = _current.ResolveNamed(named, typeof(T));
            if (obj == null)
            {
                return default;
            }
            else
            {
                return (T)obj;
            }
        }
    }
}
